<template>
  <MenuPage
    :data="resData.list"
    :columns="columns"
    :page.sync="queryParams.pageIndex"
    :size.sync="queryParams.pageSize"
    :total="resData.total"
    :title="' '"
    :loading="resData.loading"
    @queryFun="getProductTagList"
    :selection.sync="selectTagList"
    :showSelectTag="disabledAction">
    <template slot="search">
      <Button
          type="primary"
          ghost
          icon="ios-add"
          style="height: 32px;margin-left: 9px;"
          v-if="!disabledAction"
          @click="showAddAndUpdate()">创建分类标签
      </Button>
      <Input
          clearable
          v-model.trim="queryParams.name"
          placeholder="分类标签名称"
          @on-change="debounceFn"
          style="width: 180px;margin-left: 15px;" />
      <Button
          type="primary"
          ghost
          style="height: 32px;margin-left: 9px;"
          @click="refreshQueryParams()">
          <i class="el-icon-refresh-right" />
      </Button>
    </template>
    <Modal
        v-model="modalData.show"
        :title="`${isAdd ? '创建' : '修改'}标签`"
        @on-visible-change="changeVisible">
        <Form 
            ref="formInline"
            :label-width="100"
            :model="formInline" 
            :rules="ruleInline">
            <FormItem prop="name" label="标签名称">
                <Input v-model="formInline.name"></Input>
            </FormItem>
        </Form>
        <div slot="footer" class="footer">
            <Button @click="modalData.show = false">取消</Button>
            <Button @click="save" :loading="modalData.loading" type="primary">确定</Button>
        </div>
    </Modal>
  </MenuPage>
</template>

<script>
import { queryProductTagList, deleteProductTag, addProductTag, updateProductTag } from '@/view/testPlatform/asset/api/productTag.js'
import { debounce } from '@/libs/utils'
export default {
  name: 'AssetTypeComponent',
  props: {
    tagList: {
      type: Array,
      default: () => []
    },
    allowCheck: {
        type: Boolean,
        default: false
    },
    disabledAction: {
        type: Boolean,
        default: false
    }
  },
  data() {
    return {
      selectTagList: JSON.parse(JSON.stringify(this.tagList)),
      resData: {
          total: 0,
          list: [],
          loading: true
      },
      queryParams: {
          pageIndex: 1,
          pageSize: 10,
          name: '',
      },
      columns: [
          {
              title: '分类标签名称',
              key: 'name',
              tooltip: true,
          },
          {
              title: '使用次数',
              key: 'bindNum',
              tooltip: true,
          },
          {
              title: '创建者',
              key: 'creatorName',
              tooltip: true,
          },
          {
              title: '创建时间',
              key: 'created',
              tooltip: true,
          },
          {
              title: '创建时间',
              key: 'created',
              tooltip: true,
          },
          {
            title: '操作',
            slot: 'action',
            width:160,
            opList: [
              {
                txt: '修改',
                fun: (obj) => {
                  this.showAddAndUpdate(obj)
                }
              },
              {
                txt: '删除',
                tooltip: true,
                type: 'delete',
                title: '确定要删除吗？',
                fun: (obj) => {
                  this.delete(obj.id)
                }
              }
            ]
          }
      ],
      isAdd: true,
      modalData: {
          show: false,
          loading: false
      },
      formInline: {
          name: ''
      },
      ruleInline: {
          name: [
              { required: true, message: `标签名称不能为空`, trigger: 'blur,change' },
              { type:'string',max: 64,trigger:'blur,change',message:'最多输入64个字符' },
          ],
      }
    }
  },
  watch: {
    selectTagList(list) {
        this.$emit('change-tag', list)
    },
    tagList(list) {
        if (list.toString() !== this.selectTagList.toString()) {
            this.selectTagList = JSON.parse(JSON.stringify(list))
        }
    }
  },
  mounted() {
    this.getProductTagList()
    if (this.allowCheck) {
        let index = this.columns.findIndex(item => item.type === 'selection')
        if (index === -1) {
            this.columns.splice(0, 0, {
                type: 'selection',
                width: 60,
                align: 'center'
            })
        }
    }
    if (this.disabledAction) {
        let index = this.columns.findIndex(item => item.title === '操作')
        if (index !== -1) {
            this.columns.splice(index, 1)
        }
    }
  },
  methods: {
    // 隐藏模态框时，重置表单数据
    changeVisible(type) {
        if (!type) {
            this.$refs.formInline.resetFields()
            this.modalData.loading = false
        }
    },
    showAddAndUpdate(data) {
        this.isAdd = !data
        this.modalData.show = true
        let obj = data || {}
        this.formInline = Object.assign({}, obj)
    },
    // 重置搜索条件并查询数据
    refreshQueryParams() {
        this.queryParams = {
            pageIndex: 1,
            pageSize: 10,
            name: '',
        }
        this.getProductTagList()
    },
    delete(id) {
        deleteProductTag(id).then(({ code, message }) => {
            if (code !== 1) {
                this.$Message.warning(message)
                return
            }
            this.$Message.success(`删除标签成功`)
            // 删除后展示当前页，当前页没有数据展示前一页
            this.queryParams.pageIndex = (this.resData.list.length == 1 && this.queryParams.pageIndex > 1) ?
                            this.queryParams.pageIndex - 1 : this.queryParams.pageIndex;
            this.getProductTagList()
            this.$emit('delete-success', id)
        }).catch(() => {
            this.$Message.error(`删除标签异常`)
        })
    },
    // 防抖方法，用于输入型查询
    debounceFn: debounce(function() {
        this.changePageNow(1);
    }),
    // 修改当前页
    changePageNow(val) {
        this.pageIndex = val
        this.getProductTagList()
    },
    // 查询分类标签列表
    getProductTagList() {
        this.resData.loading = true
        queryProductTagList(this.queryParams).then(({ code, message, data = {} }) => {
            if (code !== 1) {
                this.$Message.warning(message)
                return
            }
            let list = data.items || []
            if (this.allowCheck) {
                let checkIds = this.selectTagList.map(item => item.id)
                this.resData = {
                    total: data.total || 0,
                    list: list.map(item => {
                        item._checked = checkIds.includes(item.id)
                        return item
                    }),
                    loading: false
                }
            } else {
                this.resData = {
                    total: data.total || 0,
                    list,
                    loading: false
                }
            }
        }).catch(() => {
            this.$Message.error('获取分类标签列表异常')
        }).finally(() => {
            this.resData.loading = false
        })
    },
    save() {
        this.$refs.formInline.validate(valid => {
            if (valid) {
                this.modalData.loading = true
                let apiName = this.isAdd ? addProductTag : updateProductTag
                let data = Object.assign({}, this.formInline)
                if (this.isAdd) { // 创建操作确认把id删掉，避免造成错误
                    delete data.id
                }
                apiName(data).then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                        return
                    }
                    // 创建成功
                    this.$Message.success(`${this.isAdd ? '创建' : '修改'}标签成功`)
                    this.refreshQueryParams()
                    this.$emit(`${this.isAdd ? 'add' : 'update'}-success`)
                    this.modalData.show = false
                }).catch(() => {
                    this.$Message.error(`${this.isAdd ? '创建' : '修改'}标签异常`)
                }).finally(() => {
                    this.modalData.loading = false
                })
            } else {

            }
        })
    },
  }
}
</script>
